import {reactive, ref, toRaw} from "vue";
import type IPageResp from "@/type/IPageResp.ts";
import resetDefault from "@/util/reset-default.ts";
import type IPageReq from "@/type/IPageReq.ts";
import type ISysUserReq from "../type/req/ISysUserReq.ts";
import type ISysUserResp from "../type/resp/ISysUserResp.ts";
import type ISysUserRoleResp from "@/view/rbac/user/type/resp/ISysUserRoleResp.ts";
import userApi from "../api/UserApi.ts";
import type TreeNodeProp from "@/components/tree/TreeNodeProp.ts";
import departApi from "@/view/rbac/depart/api/SysDepartApi.ts";
import recycleBinApi from "@/view/sys/recyclebin/api/RecycleBinApi.ts";

/**
 * user模块的CRUD代码
 */
export const useUserCrud = () => {
    /**
     * 分页数据
     */
    const pageModel = reactive<IPageReq>({
        pageNo: 1,
        pageSize: 10
    })

    /**
     * search表单数据
     */
    const searchModel = reactive<ISysUserReq>({
        userName: '',
        realName: '',
        phone: ''
    })

    /**
     * 表格数据
     */
    const tableModel = reactive<IPageResp<ISysUserResp>>({
        pageNo: 1,
        pageSize: 10,
        pages: 0,
        total: 0,
        records: []
    })

    /**
     * 新增和编辑框数据
     */
    const dialogModel = reactive<ISysUserReq>({
        userName: "",
        status_bool: true
    })

    /**
     * 分页查询
     */
    let loading = ref<boolean>(false)
    const page = () => {
        loading.value = true
        userApi.page({...toRaw(searchModel), ...toRaw(pageModel)})
            .then(result => {
                tableModel.pageNo = result.pageNo
                tableModel.pageSize = result.pageSize
                tableModel.pages = result.pages
                tableModel.total = result.total
                tableModel.records = result.records
            })
            .catch(() => {
                //查询出错，就清空数据
                tableModel.records = []
            })
            .finally(() => {
                loading.value = false
            })
    }
    const reset = () => {
        resetDefault(searchModel)
        page()
    }

    const pageChange = (pageNo: number, pageSize: number) => {
        pageModel.pageNo = pageNo
        pageModel.pageSize = pageSize
        page()
    }

    /**
     * 新增和编辑的dialog
     */
    const departTree = ref<TreeNodeProp[]>([])
    const departCheckedItems = ref<string[]>([])

    let dialogVisible = ref(false)
    const openDialog = (row: any) => {
        if (row) {
            Object.assign(dialogModel, row)
            dialogModel.status_bool = row.status === 1
            drawerVisible.value = true

            departCheckedItems.value = row.departList.map((item: ISysUserRoleResp) => item.id)
        } else {
            dialogModel.status_bool = true
            dialogVisible.value = true

            departCheckedItems.value = []
        }
        // 新增或编辑都需要使用部门
        departApi.tree().then(departs => {
            departTree.value = departs
        })
    }
    const closeDialog = () => {
        resetDefault(dialogModel)
        dialogVisible.value = false
        drawerVisible.value = false
    }
    const addOrUpdate = async () => {
        console.log(departCheckedItems.value)

        if (dialogModel.status_bool) {
            dialogModel.status = 1
        } else {
            dialogModel.status = 2
        }
        if (departCheckedItems.value.length > 0) {
            dialogModel.departList = departCheckedItems.value
        }
        await userApi.addOrUpdate(dialogModel)
        closeDialog()
        page()
    }

    const status = async (userId: string, status: number) => {
        await userApi.status({id: userId, status})
    }

    /**
     * 删除
     */
    const deleteByIds = async (ids: string[]) => {
        await userApi.deleteById(ids)
        page()
    }

    /**
     * 抽屉
     */
    const drawerVisible = ref(false)

    /**
     * 分配角色弹出框
     */
    const roleDialogVisible = ref(false)

    const userRoleSearchModel = reactive({
        roleName: '',
        roleCode: '',
    })

    const userRoleTableModel = reactive<{ currentUserId: string, data: ISysUserRoleResp[] }>({
        currentUserId: '',
        data: [],
    })

    /**
     * 查询用户角色信息
     */
    const openUserRoleDialog = async (userId: string) => {
        // 需要使用部门
        departApi.tree().then(departs => {
            departTree.value = departs
        })

        userRoleTableModel.currentUserId = userId
        roleDialogVisible.value = true
        await listUserRoles()
    }

    const closeUserRoleDialog = () => {
        departCheckedItems.value = []
        userRoleSearchModel.roleCode = ''
        userRoleSearchModel.roleName = ''
        roleDialogVisible.value = false
    }

    const listUserRoles = async () => {
        userRoleTableModel.data = await userApi.listUserRoles({
            userId: userRoleTableModel.currentUserId,
            departIds: departCheckedItems.value.join(","), ...toRaw(userRoleSearchModel)
        })
    }

    const resetUserRole = async () => {
        departCheckedItems.value = []
        userRoleSearchModel.roleCode = ''
        userRoleSearchModel.roleName = ''
        await listUserRoles()
    }

    const updateUserRole = async (roleId: string) => {
        console.log(roleId)
        departCheckedItems.value = []
        await userApi.updateUserRole(userRoleTableModel.currentUserId, roleId)
        await listUserRoles()
    }

    /**
     * 回收站
     */
    const recycleBinDialogVisible = ref(false)

    // 回收站分页数据
    const recycleBinPageModel = reactive<IPageReq>({
        pageNo: 1,
        pageSize: 10
    })

    // 回收站表格数据
    const recycleBinTableModel = reactive<IPageResp<ISysUserResp>>({
        pageNo: 1,
        pageSize: 10,
        pages: 0,
        total: 0,
        records: []
    })

    const openRecycleBinDialog = () => {
        recycleBinDialogVisible.value = true
        recycleBinApi.recycleBin("sys_user", recycleBinPageModel.pageNo, recycleBinPageModel.pageSize).then(resp => {
            recycleBinTableModel.pageNo = resp.pageNo
            recycleBinTableModel.pageSize = resp.pageSize
            recycleBinTableModel.pages = resp.pages
            recycleBinTableModel.total = resp.total
            recycleBinTableModel.records = resp.records
        }).catch(() => {
            tableModel.records = []
        }).finally(() => {
            loading.value = false
        })
    }

    const closeRecycleBinDialog = () => {
        recycleBinDialogVisible.value = false
    }

    const restore = (id: string) => {
        recycleBinApi.restore("sys_user", id).then(resp => {
            openRecycleBinDialog()
        });
    }

    const deleteCompletely = (id: string) => {
        recycleBinApi.deleteCompletely("sys_user", id).then(resp => {
            openRecycleBinDialog()
        });
    }

    const recycleBinPageChange = (pageNo: number, pageSize: number) => {
        recycleBinTableModel.pageNo = pageNo
        recycleBinTableModel.pageSize = pageSize

        recycleBinPageModel.pageNo = pageNo
        recycleBinPageModel.pageSize = pageSize
        openRecycleBinDialog()
    }

    return {
        searchModel,
        tableModel,
        dialogModel,
        loading,
        dialogVisible,
        drawerVisible,
        roleDialogVisible,
        userRoleSearchModel,
        userRoleTableModel,
        departTree,
        departCheckedItems,
        recycleBinDialogVisible,
        recycleBinTableModel,
        recycleBinPageChange,
        page,
        reset,
        pageChange,
        openDialog,
        closeDialog,
        addOrUpdate,
        status,
        deleteByIds,
        openUserRoleDialog,
        closeUserRoleDialog,
        listUserRoles,
        resetUserRole,
        updateUserRole,
        openRecycleBinDialog,
        restore,
        deleteCompletely,
        closeRecycleBinDialog
    }

}